package org.entity;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/**
 * @author armandino (at) gmail.com
 */
public class DataFixtures {
    private final EntityManager em;
    
    public DataFixtures(EntityManager em) {
        this.em = em;
    }
    
    public void initData() {
        Author camus = newAuthor("Albert Camus");
        addBook(camus, "The Stranger", "11121", 12);
        addBook(camus, "The Myth of Sisyphus", "88615", 13);
        addBook(camus, "The Myth of Sisyphus (Used)", "88615", 5);
        save(camus);
        
        Author dickens = newAuthor("Charles Dickens");
        addBook(dickens, "The Adventures of Oliver Twist", "66422", 18);
        addBook(dickens, "Great Expectations", "43557", 11);
        addBook(dickens, "Great Expectations, 2nd ed.", null, 16);
        save(dickens);
    }
    
    private Author newAuthor(String name) {
        Author author = new Author();
        author.setName(name);
        return author;
    }
    
    private Book addBook(Author author, String title, String isbn, Integer price) {
        Book book = new Book();
        book.setAuthor(author);
        book.setTitle(title);
        book.setIsbn(isbn);
        book.setPrice(price);
        author.getBooks().add(book);
        return book;
    }
    
    
    private void save(Object entity) {
        EntityTransaction tx = null;
        try {
            tx = em.getTransaction();
            tx.begin();
            em.persist(entity);
            tx.commit();
        } catch(Exception ex) {
            if(tx != null && tx.isActive())
                tx.rollback();
            throw new RuntimeException("Failed saving entity", ex);
        }
        
    }
}
